package org.cogaen.demo.state;

import java.awt.Color;
import java.awt.event.KeyEvent;

import org.cogaen.core.Core;
import org.cogaen.event.Event;
import org.cogaen.event.EventListener;
import org.cogaen.event.EventManager;
import org.cogaen.event.EventType;
import org.cogaen.event.SimpleEvent;
import org.cogaen.input.KeyPressedEvent;
import org.cogaen.java2d.ImageHandle;
import org.cogaen.java2d.Overlay;
import org.cogaen.java2d.SceneManager;
import org.cogaen.java2d.SpriteHandle;
import org.cogaen.resource.ResourceManager;
import org.cogaen.state.GameState;

public class MenuState implements GameState, EventListener {

	/** Unique name of this state. */
	public static final String NAME = "Main Menu";
	
	
	public static final EventType END_OF_MENU = new EventType("EndOfMenu");	
	public static final EventType START_PHYSICS_DEMO = new EventType("StartPhysicsDemo");	
	public static final EventType START_GAME_DEMO = new EventType("StartGameDemo");	
	
	private static final String RES_GROUP = NAME;
	
	private Core core;
	
	public MenuState(Core core) {
		this.core = core;
		
		// initialize resource group
		ResourceManager resMngr = ResourceManager.getInstance(this.core);
		resMngr.addResource(RES_GROUP, new ImageHandle("menu_img", "menu_800x600.jpg"));
		resMngr.addResource(RES_GROUP, new SpriteHandle("menu_spr", "menu_img"));
	}
	
	@Override
	public String getName() {
		return NAME;
	}

	@Override
	public void onEnter() {
		// register as event listener for key pressed events
		EventManager.getInstance(this.core).addListener(this, KeyPressedEvent.TYPE);		
		
		// load resource group
		ResourceManager.getInstance(this.core).loadGroup(RES_GROUP);
		
		// create overlay displaying menu image
		SceneManager scnMngr = SceneManager.getInstance(this.core);
		scnMngr.getScreen().hideMouseCursor();
		scnMngr.setClearBackground(true);
		scnMngr.setBackgroundColor(Color.BLACK);
		Overlay splashOvl = scnMngr.createOverlay();		
		splashOvl.addVisual( scnMngr.createSpriteVisual("menu_spr") );	
		scnMngr.centerOverlay(splashOvl);
	}

	@Override
	public void onExit() {
		EventManager.getInstance(this.core).removeListener(this);
		SceneManager.getInstance(this.core).destroyAll();
		ResourceManager.getInstance(this.core).unloadGroup(RES_GROUP);
	}

	@Override
	public void handleEvent(Event event) {
		if ( event.isOfType(KeyPressedEvent.TYPE) ) {
			KeyPressedEvent keyPressed = (KeyPressedEvent) event;
			if (keyPressed.getKeyCode() == KeyEvent.VK_ESCAPE) {
				EventManager.getInstance(this.core).enqueueEvent( new SimpleEvent(END_OF_MENU) );
			} else if (keyPressed.getKeyCode() == KeyEvent.VK_F1) {
				EventManager.getInstance(this.core).enqueueEvent( new SimpleEvent(START_PHYSICS_DEMO) );
			} else if (keyPressed.getKeyCode() == KeyEvent.VK_F2) {
				EventManager.getInstance(this.core).enqueueEvent( new SimpleEvent(START_GAME_DEMO) );
			}
		}
	}

}
